package com.gof.example.prototype.prototypemanager;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Created by zhiyuan on 2018/5/3 08:50.
 * haiming.fei@tongdun.cn
 */
public class PrototypeManager {

    private static PrototypeManager prototypeManager = new PrototypeManager();
    private ConcurrentHashMap<String, OfficeDocument> odMaps = new ConcurrentHashMap<String, OfficeDocument>();

    private PrototypeManager() {
        FarOfficeDocument farOfficeDocument = new FarOfficeDocument();
        farOfficeDocument.setName("far");
        odMaps.put(farOfficeDocument.getName(), farOfficeDocument);
        SrsOfficeDocument srsOfficeDocument = new SrsOfficeDocument();
        srsOfficeDocument.setName("srs");
        odMaps.put(srsOfficeDocument.getName(), srsOfficeDocument);
        PprOfficeDocument pprOfficeDocument = new PprOfficeDocument();
        pprOfficeDocument.setName("ppr");
        odMaps.put(pprOfficeDocument.getName(), pprOfficeDocument);

        DefaultOfficeDocument defaultOfficeDocument = new DefaultOfficeDocument();
        defaultOfficeDocument.setName("default");
        odMaps.put(defaultOfficeDocument.getName(), defaultOfficeDocument);
    }


    public static PrototypeManager getInstance() {
        return prototypeManager;
    }


    public void addDocument(OfficeDocument doc) {
        odMaps.putIfAbsent(doc.getName(), doc);
    }

    public OfficeDocument getDoc(String key) throws CloneNotSupportedException {
        OfficeDocument officeDocument = odMaps.get(key);
        if (officeDocument == null) {
            return odMaps.get("default").clone();
        } else {
            return officeDocument.clone();
        }
    }
}
